package com.telit.android.listener.excel;


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;


/**
 * @Auther amy
 * @Describe
 */
public class EasyExcelConsumerListener<T> extends AnalysisEventListener<T> {

    private int pageSize = 3000;
    private List<T> list;
    private Consumer<List<T>> consumer;

    public EasyExcelConsumerListener(int pageSize, Consumer<List<T>> consumer) {
        if (pageSize != 0) {
            this.pageSize = pageSize;
        }
        this.consumer = consumer;
        list = new ArrayList<>(pageSize);
    }

    public EasyExcelConsumerListener() {
        list = new ArrayList<>(pageSize);
    }


    @Override
    public void invoke(T data, AnalysisContext context) {
        list.add(data);
        if (list.size() >= pageSize) {
            consumer.accept(list);
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (consumer != null) {
            consumer.accept(list);
        }
    }

    public List<T> getDatas() {
        return list;
    }

    /**
     * 设置读取的数据集合
     **/
    public void setDatas(List<T> list) {
        this.list = list;
    }

}
